//
//  AppDelegate+SGPaymentOpenURL.m
//  smartGas
//
//  Created by chen on 2017/11/20.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "AppDelegate+SGPaymentOpenURL.h"
#import "UPPaymentControl.h"

#import "AppNotificationMacro.h"

@implementation AppDelegate (SGPaymentOpenURL)

#pragma mark - registerWxPayment

- (void)registerWxPayment{
    [WXApi registerApp:@"wx4318564cfc17c463"];
}

#pragma mark - HandelPaymentResult

- (void)paymentSuccessful{
    kPostNotification(kNotificationPaymentSuccess, nil);
}

- (void)paymentFailed{
    [self paymentAbnormalWithReason:@"订单支付失败"];
}

- (void)paymentAbnormalWithReason:(NSString *)reason{
    kPostNotification(kNotificationPaymentFailed, reason);
}

#pragma mark -- paymentResult

//支付宝结果
- (void)aliPayResult:(NSDictionary *)resultDic{
    
    switch ([resultDic[@"resultStatus"] integerValue]) {
        case 9000:
            DLog(@"订单支付成功");
            [self paymentSuccessful];
            break;
        case 8000:
            DLog(@"正在处理中");
            [self paymentAbnormalWithReason:@"正在处理中"];
            break;
        case 4000:
            DLog(@"订单支付失败");
            [self paymentFailed];
            break;
        case 6001:
            DLog(@"用户中途取消");
            [self paymentAbnormalWithReason:@"已取消支付"];
            break;
        case 6002:
            DLog(@"网络连接出错");
            [self paymentAbnormalWithReason:@"网络连接出错"];
            break;
        default:
            break;
    }
}

- (void)unionPayResult:(NSString *)code data:(NSDictionary *)data{
    
    if([code isEqualToString:@"success"]) {
        [self paymentSuccessful];
    }
    else if([code isEqualToString:@"fail"]) {
        //交易失败
        [self paymentFailed];
    }
    else if([code isEqualToString:@"cancel"]) {
        //交易取消
        [self paymentAbnormalWithReason:@"交易取消"];
    }else{
        [self paymentAbnormalWithReason:@"交易异常"];
    }
}


- (void)wxPaymentCode:(BaseResp *)resp{
    
    switch (resp.errCode) {
        case WXSuccess:
            [self paymentSuccessful];
            DLog(@"%@",@"支付结果：成功！");
            break;
        case WXErrCodeCommon: //普通错误类型
            [self paymentFailed];
            DLog(@"支付结果：失败！");
            break;
        case WXErrCodeUserCancel: //用户点击取消并返回
            [self paymentAbnormalWithReason:@"已退出支付"];
            DLog(@"用户已经退出支付！");
            break;
        case WXErrCodeAuthDeny:
            [self paymentAbnormalWithReason:@"授权失败"];
            DLog(@"授权失败");
            break;
        default:
        {
            NSString *result = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
            DLog(@"%@",result);
            [self paymentAbnormalWithReason:result];
        }
        break;
    }
}

#pragma mark - OpenURL

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation{
    
    DLog(@"%s \n %@ \n %@",__func__ ,url,url.host);
    if ([url.host isEqualToString:@"safepay"]) { //支付宝
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
         //授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
    }else if([url.host isEqualToString:@"uppayresult"]){
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            [self unionPayResult:code data:data];
        }];
    }
    return [WXApi handleOpenURL:url delegate:self];
}

//9.0前的方法，为了适配低版本 保留 (可以不实现，实现application:openURL:ourceApplication:annotation:）
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    DLog(@"%s \n %@ \n %@",__func__ ,url,url.host);
    
    if ([url.host isEqualToString:@"safepay"]) { //支付宝
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
         //授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
    }else if([url.host isEqualToString:@"uppayresult"]){
        
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            [self unionPayResult:code data:data];
        }];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return true ;
}

//9.0后的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    DLog(@"%s \n %@ \n %@",__func__ ,url,url.host);
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        // 需要注意的是，如果没有安装支付宝,则不会再这里回调。
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            [self aliPayResult:resultDic];
        }];
       
    }else if([url.host isEqualToString:@"uppayresult"]){
        
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            [self unionPayResult:code data:data];
        }];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

#pragma mark -- WXApiDelegate

/*
 app响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
 */
- (void)onReq:(BaseReq*)req{
}
/*
 如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
 -处理从微信客户端完成操作后返回程序之后的回调方法,显示支付结果的
 */
- (void) onResp:(BaseResp*)resp{
    //启动微信支付的response
    if([resp isKindOfClass:[PayResp class]]){
        [self wxPaymentCode:resp];
    }
}

@end
